package diycode

import (
	"fmt"
	"strconv"
	"strings"

	"gitee.com/minph/siphan/exception"
)

// 通过Unicode解码字符串
func DecodeTextByUnicode(text string) (string, error) {
	unquotedText := strconv.Quote(text)
	str, err := strconv.Unquote(strings.Replace(unquotedText, `\\u`, `\u`, -1))
	if err != nil {
		return "", err
	}
	return str, nil
}

// 通过自定义字符项数组解码
func DecodeSlice(text string, format []string, codeSlice CodeSlice) (string, error) {
	formatLen := len(format)
	arr := strings.Split(text, format[formatLen-1])
	indexArr := make([]int, len(arr))

	for i := range arr {
		str := ""
		for strLen(arr[i]) > 0 {
			errorFlag := true
			for index := range format {
				if strings.HasPrefix(arr[i], format[index]) {
					arr[i] = arr[i][strLen(format[index]):]
					str += fmt.Sprint(index)
					errorFlag = false
					continue
				}
			}

			if errorFlag {
				return "", exception.NewErrBadFormat()
			}
		}

		if strLen(str) == 0 {
			indexArr[i] = 0
		} else if num, err := strconv.ParseInt(str, 0, 0); err == nil {
			indexArr[i] = int(num)
		} else {
			return "", err
		}

	}

	for i := range indexArr {
		num := Base2to10(indexArr[i], formatLen-1)
		if item, err := codeSlice.FindIndex(num); err == nil {
			arr[i] = item.Char
		} else {
			arr[i] = ""
		}
	}

	if str, err := DecodeTextByUnicode(strings.Join(arr, "")); err != nil {
		return "", err
	} else {
		return str, nil
	}

}

// 解码
// 使用默认字符项数组
func Decode(text string, format []string) (string, error) {
	return DecodeSlice(text, format, GetCodeSlice())
}
